package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
	"mockapi/models"
	"mockapi/utils"
	"runtime/debug"
	"strings"
	"time"
)

// 初始化
func init() {
	log.SetFormatter(new(utils.Formatter))
	log.SetReportCaller(true)
	log.SetOutput(&lumberjack.Logger{
		Filename:   "./logs/api.log",
		MaxSize:    100, // megabytes
		MaxBackups: 3,
		MaxAge:     28,   // days
		Compress:   true, // disabled by default
	})
	// log.SetOutput(os.Stdout)
	log.SetLevel(log.DebugLevel)
}

func main(){
	engine := gin.New()
	engine.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		// your custom format
		logMsg := fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
		log.Info(logMsg) //logrus 记录日志
		return logMsg
	}))

	// 异常捕获
	engine.Use(SetUp())

	// 路由
	engine.GET("/check", func(c *gin.Context) {
		c.String(200, "true")
	})
	engine.GET("/userinfo", func(c *gin.Context) {
		userinfo:=&models.UserInfo{
			Id: 1,
			Username: "ABC",
			Phone: "123",
			PhoneNumber: "123456",
			ChineseName: "ddd",
			Email: "123@126.com",
			Token: "abc123",
		}
		res:=&models.UserInfoRes{
			Data:userinfo,
		}
		res.Status=true
		res.StatusCode=200
		c.JSON(200, res)
	})

	// 监听
	engine.Run(":8080")
}

func SetUp() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				DebugStack := ""
				for _, v := range strings.Split(string(debug.Stack()), "\n") {
					DebugStack += v + "\n"
				}
				fmt.Printf(DebugStack)
				log.Error(DebugStack)
				c.JSON(500, err)
			}
		}()
		c.Next()
	}
}